package gui;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.game.Sprite;

import logic.Engine;
import logic.EngineBluetoothGame;
import logic.LogicHelper;
import logic.MainMidlet;
import logic.DataSaverLoader;

/**
 * screen for ingame menu - during play
 * @author Rekin
 *
 */
public class IngameMenuCanvas extends MenuCanvas{
	private static String[] menuItemsNames = {
		"Resume game",
		"Save game",
		"Main menu",
	};
	private Engine engine;

	/**
	 * menu constructor
	 * @param canSave determines if save button is available
	 * @param en Engine class object from with data will be fetched
	 */
	public IngameMenuCanvas(boolean canSave, Engine en) {
		super(menuItemsNames);
		if(!canSave){
			getMenuItem(1).setEnabled(false);
		}
		else{
			getMenuItem(1).setEnabled(true);
		}
		engine=en;
	}
	
	/**
	 * handles pressing buttons
	 */
	protected void menuItemPressed(int buttonIndex)
	{
		super.menuItemPressed(buttonIndex);
		
		if( buttonIndex == 0){
	    	MainMidlet.getMidletInstance().showResumeBoard();
	    }
	    else if(buttonIndex == 1){
	    	if(!getMenuItem(1).isEnabled()){
	    		return;
	    	}
	    	DataSaverLoader saver = new DataSaverLoader();
	    	if(saver.saveGameState(engine)){
	    		Alert pop = LogicHelper.makePopup("Success",
	    				"Game saved to file.", 3000, AlertType.CONFIRMATION);
	    		MainMidlet.getMidletInstance().setDisplay(pop);
	    	}
	    	else{
	    		Alert pop = LogicHelper.makePopup("Error",
	    				"Unable to save game.", 3000, AlertType.ERROR);
	    		MainMidlet.getMidletInstance().setDisplay(pop);
	    	}
	    }
	    else if(buttonIndex == 2){
	    	MainMidlet.getMidletInstance().showMainMenu();
	    	if(engine instanceof EngineBluetoothGame){
	    		((EngineBluetoothGame)engine).closeConnections();
	    	}
	    }
	}
	
	/**
	 * @Override
	 * handles creating selection sprites
	 */
	protected void initSprites() {
		selectionElement1 = new Sprite(LogicHelper.createImageFromResources("/rotatingCards/leftSelectSequence.png", this), 30, 30);
		selectionElement2 = new Sprite(LogicHelper.createImageFromResources("/rotatingCards/rightSelectSequence.png", this), 30, 30);
	}
}
